<template>
  <div class="templates bg-white form-container">
    <div class="operation-container">
      <el-button type="primary" @click="openDialogForm(defaultForm, false)" size="small">新增一级菜单</el-button>
    </div>
    <div class="purview-container">
      <el-tree :data="treeData" node-key="id" :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        :draggable="true" @node-drop="handleDrop">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.PurviewName }}</span>
          <span>
            <el-button
              type="text"
              size="mini"
              @click="() => openDialogForm(data, false)"
              class="text-primary"
            >添加</el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => openDialogForm(data, true)"
              class="text-success"
            >修改</el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
              class="text-danger"
            >删除</el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogForm">
      <el-form :model="form">
        <el-form-item label="所属权限" :label-width="formLabelWidth" v-if="!isEdit">{{form.FatherName}}</el-form-item>
        <el-form-item label="权限名称" :label-width="formLabelWidth">
          <el-input v-model="form.PurviewName"></el-input>
        </el-form-item>
        <el-form-item label="主页URL" :label-width="formLabelWidth">
          <el-input v-model="form.PageUrl"></el-input>
        </el-form-item>
        <el-form-item label="组件名称" :label-width="formLabelWidth">
          <el-input v-model="form.componentName"></el-input>
        </el-form-item>
        <el-form-item label="icon" :label-width="formLabelWidth">
          <el-input v-model="form.icon"></el-input>
        </el-form-item>
        <el-form-item label="权限列表" :label-width="formLabelWidth">
          <el-input v-model="form.PurviewUrls"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">取 消</el-button>
        <el-button type="primary" @click="sureDialogForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { purviewList } from '../../models/fake-data'
export default {
  name: 'purview',
  props: [],
  data() {
    return {
      treeData: [],
      dialogForm: false,
      formLabelWidth: '120px',
      form: {
        PurviewName: '',
        PurviewId: '',
        FatherId: '',
        PageUrl: '',
        PurviewUrls: '',
        componentName: '',
        icon: '',
      },
      dialogTitle: '',
      isEdit: false,
      defaultForm: {
        PurviewId: 0
      },
      defaultExpandedKeys: [], // 默认展开节点的 key 的数组
      editFatherId: [], // 当前修改的父节点
    }
  },
  mounted() {
    this.allPurview();
  },
  methods: {
    /**
     * 获得权限数据
     */
    allPurview: function () {
      this.treeData = purviewList;
      let defaultExpandedKeys = [];
      for (let index = 0; index < (this.treeData || []).length; index++) {
        const item = this.treeData[index];
        defaultExpandedKeys.push(item.id);
      }
      defaultExpandedKeys = defaultExpandedKeys.concat(this.editFatherId);
      this.defaultExpandedKeys = defaultExpandedKeys;
    },

    openDialogForm(data, isEdit) {
      this.dialogForm = true;
      this.form = data;
      this.isEdit = isEdit;
      if (this.isEdit) {
        this.form = data;
        this.dialogTitle = '修改权限';
      } else {
        this.form = {
          FatherId: data.PurviewId,
          FatherName: data.PurviewName,
        };
        this.dialogTitle = '添加权限';
      }
    },

    async sureDialogForm() {
      try {
        let req = this.form;
        if (!req.PageUrl) {
          req.PageUrl = "";
        }
        if (!req.PurviewUrls) {
          req.PurviewUrls = "";
        }
        console.log('请求参数', req);
        let url = this.isEdit ? 'purviewEdit' : 'purviewAdd'
        if (this.form && this.form.FatherId) {
          this.editFatherId = [this.form.FatherId]
        }
        this.$message.success('保存成功');
        this.dialogForm = false;
      } catch (error) {
        this.$message.warning(error && error.message || '保存失败');
      }
    },


    remove(node, data) {
      this.$confirm(`确认要删除【${data.PurviewName}】吗?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message.success('删除成功');
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      }).catch(() => {

      });
    },


    // 拖拽完成
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let req = {};
      // 是否添加在最后一层级
      if (dropType && dropType == 'inner') {
        let purviews = dropNode.data && (dropNode.data.children || []).map((item, index) => {
          return {
            purviewId: item.PurviewId,
            sort: index + 1,
          }
        })

        req = {
          fatherId: dropNode.data && dropNode.data.PurviewId,
          purviews: purviews,
        }
      } else {
        let purviews = dropNode.parent && (dropNode.parent.childNodes || []).map((item, index) => {
          return {
            purviewId: item.data && item.data.PurviewId,
            sort: index + 1,
          }
        })

        req = {
          fatherId: dropNode.data && dropNode.data.FatherId,
          purviews: purviews,
        }
      }

      this.updatePurviewSort(req)
    },

    async updatePurviewSort(req) {
      try {
        if (req && req.fatherId) {
          this.editFatherId = [req.fatherId]
        }
        console.log('修改顺序请求参数', req);
        this.$message.success('保存成功');
        this.allPurview();
      } catch (e) {
        this.$message.warning(e && e.message || '保存失败');
        this.allPurview();
      }
    }
  }
}
</script>
<style lang="scss">
.purview-container {
  padding: 20px;
  width: 400px;

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
